package OrderService

import (
	"context"
	"errors"
	"gdshop-back-end-go/client-api/app/request/OrderReq"
	"gdshop-back-end-go/client-api/app/response/OrderResp"
	"gdshop-back-end-go/common/db"
	"gdshop-back-end-go/common/libs/genids"
	"gdshop-back-end-go/common/response"
	"github.com/gogf/gf/database/gdb"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/util/gconv"
	"github.com/syyongx/php2go"
	"time"
)

// 用户关闭订单 判断状态，必须是 1待付款 才可以关闭订单
func SaveOrderSubAftersale(ctx context.Context, parames *OrderReq.SaveOrderSubAftersale) *response.JsonResponse {
	allowRefundType := []int{
		1,
		2,
	}

	if !php2go.InArray(parames.RefundType, allowRefundType) {
		return response.FailByRequestMessage(nil, "不支持的类型")
	}

	var osModel OrderResp.SubOrder
	err := db.GetUnSafaTableAddDeleteWhere(ctx, "order_sub").Where("id", parames.OrderSubId).
		Struct(&osModel)
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}

	if !IsMyOrder(ctx, osModel.OrderId, parames.MemberId) {
		return response.FailByRequestMessage(nil, "请勿操作别人的订单")
	}

	if osModel.RefundStatus != 0 && osModel.RefundStatus != 2 {
		return response.FailByRequestMessage(nil, "不能重复申请售后")
	}

	count, err := db.GetUnSafaTableAddDeleteWhere(ctx, "order_refund").
		Where("order_sub_id = ? AND status IN (?)", parames.OrderSubId, []int{
			1,
			3,
		}).Fields("1").Count()
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}

	if count > 0 {
		return response.FailByRequestMessage(nil, "不能重复申请售后02")
	}

	if parames.RefundType == 1 {
		// 判断货物状态和退款金额
		if parames.GoogdsStatus == 2 {
			if parames.ApplyMoney > osModel.Paid {
				return response.FailByRequestMessage(nil, "退款金额不能大于实付金额")
			}
		}
		// 如果选择未收到货物，直接全额退款
		if parames.GoogdsStatus == 1 {
			parames.ApplyMoney = osModel.Paid
		}
	}
	if parames.RefundType == 2 {
		if parames.ExpressSn == "" || parames.Express == "" {
			return response.FailByRequestMessage(nil, "请填写快递公司和快递单号")
		}
	}

	refundNo, idErr := genids.ToolsGetNextId()
	if idErr != nil {
		return response.FailByRequestMessage(nil, idErr.Error())
	}
	data := g.Map{
		"order_id":     osModel.OrderId,
		"order_sub_id": osModel.Id,
		"apply_id":     parames.MemberId,
		"refund_no":    "R" + gconv.String(refundNo),
		"refund_type":  parames.RefundType,
		"reason_type":  parames.ReasonType,
		"apply_remark": parames.ApplyRemark,
		"apply_time":   time.Now().Unix(),
		"apply_money":  parames.ApplyMoney,
		"express_com":  parames.Express,
		"express":      parames.Express,
		"express_sn":   parames.ExpressSn,
		"create_at":    time.Now().Unix(),
	}
	txerr := g.DB().Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error {
		_, err := tx.Model("order_refund").Unscoped().InsertAndGetId(data)
		if err != nil {
			return err
		}
		update, err := tx.Model("order_sub").Unscoped().Where("id", parames.OrderSubId).
			Update(g.Map{
				"refund_status": 1,
			})
		if err != nil {
			return err
		}
		affected, err := update.RowsAffected()
		if err != nil {
			return err
		}
		if affected < 1 {
			return errors.New("更新失败")
		}
		return nil
	})
	if txerr != nil {
		return response.FailByRequestMessage(nil, txerr.Error())
	}
	return response.SuccessByRequestMessage(nil, "成功")
}
